package com.example.android.ouactivity.login_register;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.android.ouactivity.MainActivity;
import com.example.android.ouactivity.R;
import com.example.android.ouactivity.model.LoginBean;
import com.example.android.ouactivity.utils.HttpUtils;
import com.google.gson.Gson;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Login extends AppCompatActivity {
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = msg.obj.toString();
            Gson gson = new Gson();
            LoginBean login = gson.fromJson(result,LoginBean.class);
            if(login.getCode()==1){
                String info = login.getUser()+","+username+","+password;
                saveUserInfo(info);
                Toast.makeText(Login.this,login.getMessage(),Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Login.this, MainActivity.class);
                startActivity(intent);
            }else {
                Toast.makeText(Login.this,login.getMessage(),Toast.LENGTH_SHORT).show();
            }
        }
    };
    private String postString,username,password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        //设置返回，及页面标题
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        if (actionBar != null) {
            actionBar.setTitle("评论");
        }
        final EditText txtUsername = (EditText) findViewById(R.id.txtUsername);
        final EditText txtPassword = (EditText) findViewById(R.id.txtPassword);
        Button btnLogin = (Button) findViewById(R.id.btnLogin);
        Button btnRegister = (Button) findViewById(R.id.btnRegister);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = txtUsername.getText().toString();
                password = Login.md5(txtPassword.getText().toString());
                Log.i("Login", username);
                Log.i("Login", password);
                if (!username.equals("") && !password.equals("")) {
                    postString = "username="+username+"&password="+password;
                    HttpUtils httpUtils = new HttpUtils();
                    httpUtils.getWebJsonByPost("http://www.chqing.cn/login",handler,postString);
                } else {
                    Toast.makeText(Login.this, "请输入完整信息", Toast.LENGTH_LONG).show();
                }
            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Login.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

    }

    //MD5加密 对用户名和密码自行加密
    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh,MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh,UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
    public void saveUserInfo(String info){
        FileOutputStream fos = null;
        try {
            fos = openFileOutput("userInfo", MODE_PRIVATE);//获取文件输出流
            fos.write(info.getBytes());//保存用户名和密码
            fos.flush();   //清除缓存
//            Toast.makeText(Login.this, "保存成功", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //左上角返回的监听
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}
